<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{% block title %}OnlineJudge{% endblock %}</title>

  <!-- 外部资源 -->
  <script src="https://cdn.tailwindcss.com"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" 
        integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" 
        crossorigin="anonymous" referrerpolicy="no-referrer" />
  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.8/dist/chart.umd.min.js"></script>
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
  <link rel="icon" type="image/png" href="{{ url_for('static', filename='images/logo.png') }}">

  <!-- Tailwind 配置 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            success: '#00B42A',
            warning: '#FF7D00',
            danger: '#F53F3F',
            dark: '#1D2129',
            'dark-2': '#4E5969',
            'light-1': '#F2F3F5',
            'light-2': '#E5E6EB',
          },
          fontFamily: {
            inter: ['Inter', 'sans-serif'],
          },
        }
      }
    }
  </script>

  <!-- 自定义工具类 -->
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto { content-visibility: auto; }
      .text-shadow { text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); }
      .card-hover { transition: all 0.3s ease; }
      .card-hover:hover { 
        transform: translateY(-5px); 
        box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); 
      }
      .btn-primary { 
        @apply bg-primary text-white px-4 py-2 rounded-lg transition-all duration-300 
               hover:bg-primary/90 focus:ring-2 focus:ring-primary/50 focus:outline-none; 
      }
      .btn-secondary { 
        @apply bg-white text-dark border border-light-2 px-4 py-2 rounded-lg transition-all duration-300 
               hover:bg-light-1 focus:ring-2 focus:ring-light-2 focus:outline-none; 
      }
      .btn-danger { 
        @apply bg-danger text-white px-4 py-2 rounded-lg transition-all duration-300 
               hover:bg-danger/90 focus:ring-2 focus:ring-danger/50 focus:outline-none; 
      }
      .form-input { 
        @apply w-full px-4 py-2 rounded-lg border border-light-2 focus:border-primary focus:ring-2 focus:ring-primary/20 
               transition-all duration-300 outline-none; 
      }
      .nav-link { 
        @apply text-dark flex items-center space-x-2 text-base font-medium 
               hover:text-primary transition-colors duration-300; 
      }
      .nav-link.active { @apply text-primary border-b-2 border-primary pb-1; }
      #user-menu-container { @apply relative w-40; }
      #user-menu-button { 
        @apply flex items-center space-x-2 w-full px-3 py-2 rounded-md border border-light-2 bg-white 
               hover:bg-light-1 transition-colors duration-300; 
      }
      #user-menu { 
        @apply absolute right-0 mt-2 z-10 w-40 bg-white border border-light-2 rounded-md shadow shadow-md; 
      }
      #user-menu a { 
        @apply flex items-center space-x-2 px-3 py-2 text-sm text-dark 
               hover:bg-light-1 transition-colors duration-300; 
      }
      .flash-toast { 
        @apply fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 
               rounded-lg shadow-lg p-6 text-center z-50 
               opacity-0 scale-95 transition-all duration-300; 
      }
      .flash-toast.show { @apply opacity-100 scale-100; }
      .flash-toast.success { @apply bg-success/10 border border-success/30 text-success/80; }
      .flash-toast.danger { @apply bg-danger/10 border border-danger/30 text-danger/80; }
      .flash-toast.warning { @apply bg-warning/10 border border-warning/30 text-warning/80; }
      
      .notify-badge {
        position: absolute !important; 
        top: -2px !important; 
        right: -2px !important; 
        width: 10px !important; 
        height: 10px !important; 
        background-color: red !important; 
        border-radius: 50% !important; 
        display: flex !important; 
        align-items: center !important; 
        justify-content: center !important; 
        opacity: 1 !important; 
        /* 强制覆盖隐藏，由 JS 控制 */
      }
      .notify-badge.hidden {
        display: none !important;
      }
      
    }
  </style>
</head>

<body class="font-inter bg-gray-50 text-dark min-h-screen flex flex-col">

  <!-- 导航栏（通过 hide_nav 控制显示） -->
  {% if not hide_nav %}
  <nav class="bg-white shadow-md sticky top-0 z-50">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex items-center h-16">
      <!-- 左侧Logo和导航 -->
      <div class="flex items-center space-x-6">
        <a href="{% if current_user.is_authenticated and current_user.username == 'root' %}{{ url_for('admin_dashboard') }}{% else %}{{ url_for('problems') }}{% endif %}" class="flex-shrink-0 flex items-center">
          <i class="fas fa-code text-primary text-2xl mr-2"></i>
          <span class="text-xl font-bold text-dark">Online Judge</span>
        </a>

        <div class="hidden sm:flex space-x-6">
          <!-- 题库：所有用户可见 -->
          {% if current_user.is_authenticated and current_user.username != 'root' %}
          <a href="{{ url_for('problems') }}" data-nav="problems"
             class="nav-link {% if request.endpoint == 'problems' %}active{% endif %}">
            <i class="fas fa-list-ul"></i>  题库
          </a>
          {% endif %}

          <!-- 收藏夹：仅非游客可见 -->
          {% if current_user.is_authenticated and current_user.username != 'guest' and current_user.username != 'root'%}
          <a href="{{ url_for('my_favorites') }}" data-nav="favorites"
             class="nav-link {% if request.endpoint == 'my_favorites' %}active{% endif %}">
            <i class="fas fa-star"></i>  收藏夹
          </a>
          {% endif %}

          <!-- 提交记录：所有用户可见 -->
          {% if current_user.is_authenticated and current_user.username != 'root' %}
          <a href="{{ url_for('submissions') }}" data-nav="submissions"
             class="nav-link {% if request.endpoint == 'submissions' %}active{% endif %}">
            <i class="fas fa-history"></i>  提交记录
          </a>
          {% endif %}

          {% if current_user.is_authenticated and current_user.username != 'root' %}
          <!-- 每日打卡：所有用户可见 -->
          <a href="{{ url_for('clock_in') }}" data-nav="clock_in"
             class="nav-link {% if request.endpoint == 'clock_in' %}active{% endif %}">
            <i class="fas fa-calendar-check-o"></i>  每月打卡
          </a>
          {% endif %}

          <!-- 排行榜：仅非游客可见 -->
          {% if current_user.is_authenticated and current_user.username != 'guest' and current_user.username != 'root' %}
          <a href="{{ url_for('rank') }}" data-nav="rank"
             class="nav-link {% if request.endpoint == 'rank' %}active{% endif %}">
            <i class="fas fa-trophy"></i>  排行榜
          </a>
          {% endif %}

          <!-- 论坛：都可见 -->
          {% if current_user.is_authenticated and current_user.username != 'root' %}
          <a href="{{ url_for('forum_index') }}" data-nav="forum"
             class="nav-link {% if 'forum' in request.endpoint %}active{% endif %}">
            <i class="fas fa-comments"></i>  集市
          </a>
          {% endif %}

        </div>
      </div>

      <!-- 右侧：通知图标 + 用户菜单 -->
      <div class="ml-auto flex items-center">
        {% if user %}
          <!-- 🔴 通知图标 + 小红点（父元素必须是 relative） -->
          <div class="relative mr-4">
            <a href="{{ url_for('notifications') }}" class="text-gray-600 hover:text-primary transition-colors">
              <i class="fas fa-bell text-xl"></i>
              <!-- 红点容器：无硬编码内容，仅通过 CSS 显示背景 -->
              <span id="unread-count" class="notify-badge"></span>
            </a>
          </div>
        {% endif %}

        <!-- 用户菜单 -->
        {% if user %}
        <div id="user-menu-container">
          <button type="button" id="user-menu-button" class="flex items-center space-x-2">
            {% if user.avatar %}
              <img 
                src="{{ url_for('static', filename='uploads/avatars/' + user.avatar) }}" 
                alt="用户头像" 
                class="w-6 h-6 rounded-full object-cover"
              >
            {% else %}
              <img 
                src="{{ url_for('static', filename='uploads/avatars/default.jpg') }}" 
                alt="默认头像" 
                class="w-6 h-6 rounded-full object-cover"
              >
            {% endif %}
            <span class="text-sm font-medium">{{ user.username }}</span>
          </button>
          <div class="hidden" id="user-menu">
            <!-- 我的提交：所有登录用户可见（包括游客） -->
            {% if current_user.is_authenticated and current_user.username != 'root'%}
            <a href="{{ url_for('submissions') }}">
              <i class="fas fa-history text-base"></i>  我的提交
            </a>
            {% endif %}

            <!-- 我的收藏：仅非游客可见 -->
            {% if current_user.is_authenticated and current_user.username != 'guest' and current_user.username != 'root'%}
            <a href="{{ url_for('my_favorites') }}">
              <i class="fas fa-star text-base"></i>  我的收藏
            </a>
            {% endif %}

            <a class="dropdown-item" href="{{ url_for('user_posts') }}">
              <i class="fas fa-file-alt mr-2"></i> 帖子管理
            </a>

            <!-- 帖子审核（仅 root 可见） -->
            {% if current_user.username == 'root' %}
            <a href="{{ url_for('forum_audit') }}">
              <i class="fas fa-gavel text-base"></i>  帖子审核
            </a>
            {% endif %}

            <!-- 个人设置：仅非游客可见 -->
            {% if current_user.is_authenticated and current_user.username != 'guest' and current_user.username != 'root'%}
            <a href="{{ url_for('user_settings') }}">
              <i class="fas fa-cog text-base"></i>  个人设置
            </a>
            {% endif %}

            <!-- 退出登录：所有登录用户可见（包括游客） -->
            <a href="#" onclick="logout()">
              <i class="fas fa-sign-out text-base"></i>  退出登录
            </a>
          </div>
        </div>
        {% else %}
          <a href="{{ url_for('login') }}" class="text-dark-2 hover:text-primary mr-3">登录</a>
          <a href="{{ url_for('register') }}" class="btn-primary">注册</a>
        {% endif %}
      </div>
    </div>
  </nav>
  {% endif %}

  <!-- 主内容区 -->
  <main class="flex-grow">
    <div class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
      <!-- 全局弹窗 -->
      <div id="flash-toast" class="flash-toast"></div>
      
      {% block content %}
      <p class="text-center text-gray-500">加载中...</p>
      {% endblock %}
    </div>  
  </main>

  <!-- 页脚（通过 hide_nav 控制显示） -->
  {% if not hide_nav %}
  <footer class="bg-dark text-white py-8">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
      <div class="flex flex-col md:flex-row items-center justify-center">
        <div class="mb-4 md:mb-0">
          <div class="flex items-center">
            <i class="fas fa-code text-primary text-2xl mr-2"></i>
            <span class="text-xl font-bold">Online Judge</span>
          </div>
          <p class="text-gray-400 mt-2">一个简单的在线判题系统</p>
        </div>
      </div>
      <div class="border-t border-gray-800 mt-8 pt-8 text-center text-gray-400">
        <p>&copy; 2025 Online Judge. 保留所有权利。</p>
      </div>
    </div>
  </footer>
  {% endif %}

  <!-- 核心脚本 -->
  <script>
    // 用户菜单切换
    document.getElementById('user-menu-button')?.addEventListener('click', () => {
      const menu = document.getElementById('user-menu');
      menu?.classList.toggle('hidden');
    });

    // 点击空白处关闭用户菜单
    document.addEventListener('click', (e) => {
      const menuContainer = document.getElementById('user-menu-container');
      const menu = document.getElementById('user-menu');
      if (menuContainer && !menuContainer.contains(e.target)) {
        menu?.classList.add('hidden');
      }
    });

    // 导航激活态 + 未读通知小红点（合并逻辑）
    document.addEventListener('DOMContentLoaded', () => {
      // 1. 导航激活态处理
      const navLinks = document.querySelectorAll('.nav-link');
      navLinks.forEach(link => {
        if (link.href === window.location.href) {
          link.classList.add('active');
        }
      });
      const userMenuItems = document.querySelectorAll('#user-menu a');
      userMenuItems.forEach(item => {
        if (item.href === window.location.href) {
          item.classList.add('bg-light-1');
        }
      });

      // 2. 未读通知小红点处理（核心修复：确保仅执行一次）
      {% if user %}
          // 1. 强制打印接口响应（调试用）
          fetch('{{ url_for('unread_notify_count') }}')
            .then(response => {
              console.log('接口响应状态:', response.status); // 应为 200
              return response.json();
            })
            .then(data => {
              console.log('未读数量:', data.count); // 应与数据库一致
              const badge = document.getElementById('unread-count');
              if (!badge) {
                console.error('错误：未找到红点元素（ID: unread-count）');
                return;
              }
              // 2. 仅控制显示/隐藏
              if (data.count > 0) {
                badge.classList.remove('hidden');
              } else {
                badge.classList.add('hidden');
              }
            })
            .catch(error => {
              console.error('获取未读通知失败:', error); // 捕获网络错误
            });
        {% endif %}
      });

    // 退出登录
    function logout() {
      alert('退出登录成功');
      window.location.href = "{{ url_for('login') }}";
    }

    // 全局弹窗逻辑
    document.addEventListener('DOMContentLoaded', () => {
      const flashToast = document.getElementById('flash-toast');
      const flashMessage = document.createElement('div');
      flashMessage.id = 'flash-message';
      flashMessage.className = 'text-lg font-medium';
      flashToast.appendChild(flashMessage);

      const messages = {{ get_flashed_messages(with_categories=true) | tojson }};
      messages.forEach(([category, rawMsg]) => {
        try {
          const msgData = JSON.parse(rawMsg);
          flashMessage.innerHTML = msgData.message.replace('{count}', `<span id="countdown">${msgData.count || 3}</span>`);
          flashToast.className = `flash-toast ${category} show`;

          if (msgData.password_changed) {
            const countdownEl = document.getElementById('countdown');
            let count = parseInt(msgData.count) || 3;
            const timer = setInterval(() => {
              count--;
              countdownEl.textContent = count;
              if (count <= 0) {
                clearInterval(timer);
                window.location.href = "{{ url_for('login') }}";
              }
            }, 1000);
          } else {
            setTimeout(() => {
              flashToast.classList.remove('show');
            }, 3000);
          }
        } catch (e) {
          flashMessage.textContent = rawMsg;
          flashToast.className = `flash-toast ${category} show`;
          setTimeout(() => {
            flashToast.classList.remove('show');
          }, 3000);
        }
      });
    });

    // 点击空白处关闭弹窗
    document.addEventListener('click', (e) => {
      const flashToast = document.getElementById('flash-toast');
      if (flashToast?.classList.contains('show') && !flashToast.contains(e.target)) {
        flashToast.classList.remove('show');
      }
    });

    // 删除确认模态框逻辑
    document.addEventListener('DOMContentLoaded', () => {
      const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
      
      document.querySelectorAll('[data-bs-target="#deleteModal"]').forEach(btn => {
        btn.addEventListener('click', (e) => {
          e.preventDefault();
          const problemId = btn.getAttribute('data-problem-id');
          const problemTitle = btn.getAttribute('data-problem-title');
          
          if (problemTitle) {
            document.getElementById('problemTitle').textContent = problemTitle;
          }
          
          if (problemId) {
            document.getElementById('deleteForm').action = `/admin/problems/delete/${problemId}`;
          }
          
          deleteModal.show();
        });
      });
    });
  </script>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

  {% block scripts %}{% endblock %}
</body>
</html>